package com.example.newsdemo.fragment;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.newsdemo.R;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class HomeFragment extends Fragment {
    private ArrayList<String> mTabList=new ArrayList<>(Arrays.asList("头条","国内","国际","娱乐","体育","军事","科技","财经","时尚","游戏","汽车","健康"));
    private List<Fragment> newsListFragment=new ArrayList<>();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root=inflater.inflate(R.layout.fragment_home,container,false);
        intiView(root);
        return root;

    }
    private void intiView(View view){
        TabLayout newsTable=view.findViewById(R.id.home_news_tab);
        ViewPager newsPager=view.findViewById(R.id.home_news_pager);
        for (int i=0;i<mTabList.size();i++) {
            newsListFragment.add(new NewsListFragment());
        }
        NewsPagerAdapter adapter=new NewsPagerAdapter(requireActivity().getSupportFragmentManager()
                ,FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);

        newsPager.setAdapter(adapter);
        newsTable.setupWithViewPager(newsPager,true);

    }
    class  NewsPagerAdapter extends FragmentPagerAdapter{


        public NewsPagerAdapter(@NonNull FragmentManager fm, int behavior) {
            super(fm, behavior);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return newsListFragment.get(position);
        }

        @Override
        public int getCount() {
            return mTabList.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return mTabList.get(position);
        }
    }


    }
